// Copyright 2024 Vadim Kharitonovich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package packet

import "encoding/binary"

var (
	ResponseUnsupported           = *newResponse(ResponseCodeUnsupported)
	ResponseUnsupportedSerialized = SerializeResponse(&ResponseUnsupported)
)

type ResponseHeader struct {
	*Header[ResponseMessageCode]
	Index uint64
}

func (r *ResponseHeader) SerializeInto(buf []byte) {
	r.Header.SerializeInto(buf)
	binary.BigEndian.PutUint64(buf[HeaderSize:], r.Index)
}

type Response struct {
	*ResponseHeader
	Payload []byte
	err     error
}

func newResponse(code ResponseMessageCode) *Response {
	return &Response{
		ResponseHeader: &ResponseHeader{
			Header: &Header[ResponseMessageCode]{
				Version: version,
				Code:    code,
			},
		},
	}
}

func (r *Response) WithError(err error) *Response {
	r.err = err
	return r
}

func (r *Response) WithPayload(payload []byte) *Response {
	r.Payload = payload
	return r
}

func (r *Response) WithIndex(index uint64) *Response {
	r.Index = index
	return r
}

func NewResponseError(err error) *Response {
	return newResponse(ResponseCodeErr).WithError(err)
}

func NewResponseNext(index uint64, payload []byte) *Response {
	return newResponse(ResponseNext).WithIndex(index).WithPayload(payload)
}

func SetResponsePayload(payload []byte, buf []byte) {
	copy(buf[ResponseHeaderSize:], payload)
}

func GetResponsePayload(buf []byte) []byte {
	return buf[ResponseHeaderSize:]
}

func SerializeResponse(response *Response) []byte {
	var (
		buf = make([]byte, ResponseHeaderSize+len(response.Payload))
	)

	response.ResponseHeader.SerializeInto(buf)
	SetResponsePayload(response.Payload, buf)
	return buf
}

func ParseResponse(data []byte) (*Response, error) {
	if len(data) < ResponseHeaderSize {
		return nil, ErrMalformed
	}

	var (
		response = Response{
			ResponseHeader: &ResponseHeader{
				Header: &Header[ResponseMessageCode]{
					Version: UnserializeVersion(data),
					Code:    GetMessageCode[ResponseMessageCode](data),
				},
				Index: binary.BigEndian.Uint64(data[HeaderSize:]),
			},
			Payload: GetResponsePayload(data),
		}
	)

	return &response, nil
}
